package org.lib.mongodbhello.basic;

import java.util.Objects;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.MongoDatabaseFactory;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.mongodb.MongoClientSettings;
import com.mongodb.client.MongoDatabase;
import com.mongodb.connection.ClusterSettings;
import com.mongodb.connection.ServerSettings;

import lombok.extern.slf4j.Slf4j;

@RestController
@RequestMapping(value="/basic")
@Slf4j
public class BasicController {

	@Autowired
	private MongoClientSettings mongoClientSettings;
	
	@Autowired
	private MongoDatabaseFactory mongoDatabaseFactory;
	
	@GetMapping(value="/settings")
	public String settings() {
		log.info("mongoClientSettings={}", mongoClientSettings);
		
		StringBuffer sb = new StringBuffer();
		// 单机 null
		sb.append(mongoClientSettings.getApplicationName()).append(";\r\n");
		
		ClusterSettings cset = mongoClientSettings.getClusterSettings();
		log.info("mongoClientSettings cset={}", cset);
		if (Objects.nonNull(cset)) {
			// 单机 null
			sb.append(cset.getRequiredReplicaSetName()).append(";\r\n");
			// 有值 其中，mode=SINGLE
			sb.append(cset.getShortDescription()).append(";\r\n");
			// 单机 null
			sb.append(cset.getSrvHost()).append(";\r\n");
		}
		
		ServerSettings sset = mongoClientSettings.getServerSettings();
		log.info("mongoClientSettings sset={}", sset);
//		if (Objects.nonNull(sset)) {
//			// 无可返回内容
//		}
		
		return sb.toString();
	}
	
	@GetMapping(value="/factory")
	public String factory() {
		log.info("mongoDatabaseFactory={}", mongoDatabaseFactory);
		
		StringBuffer sb = new StringBuffer();
		MongoDatabase mdb = mongoDatabaseFactory.getMongoDatabase();
		log.info("mongoDatabaseFactory mdb={}", mdb);
		if (Objects.nonNull(mdb)) {
			// 单机  test
			sb.append(mdb.getName()).append(";\r\n");
		}
		
		return sb.toString();
	}
	
}
